import { useEventListener } from "@vueuse/core";
import { isNumber } from "@pureadmin/utils";
import { Directive, type DirectiveBinding } from "vue";
import { RuleList } from './field-length-const'


const regexList = new Map<string, any>([
  ['positivelnteger', /[^1-9]\d{0,10}$/g],//正整数，不包含0
  ['number', /[^?-\d]/g],// 数字
]);


/** input输入框长度、规则限制 */
export const inputRule: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value, arg } = binding;

    let { maxlength, max, min } = value;
    let regex = regexList.get(arg);
    console.log(regex);

    // 适用于特殊字段,如：lot id 、carrier id、wafer id ......
    if (RuleList.has(value.type)) {
      maxlength = RuleList.get(value.type).length;
      regex = RuleList.get(value.type).regex;
    }
    console.log(regex);

    useEventListener(el, 'input', () => {
      const node = el.querySelector('input')
      node.value = vauleHandle(node.value, maxlength, max, min, regex);
    });


  },
};

/**
 * @description 输入值处理
 * @param value  需要校验的字符
 * @param maxlength 最大长度
 * @param max 最大值
 * @param min 最小值
 * @param regex 正则
 * **/
function vauleHandle(value: string, maxlength: number, max, min, regex): string {
  // 根据表达式取值
  let targetValue = regex ? value.replace(regex, '') : value;
  // 根据最大长度
  if (isNumber(maxlength)) {
    const { sum, end } = checkLength(targetValue, maxlength);
    if (sum >= maxlength) {
      targetValue = targetValue.substring(0, end);
    }
  }
  // 根据最大最小取值
  if (isNumber(max) || isNumber(min)) {
    if (Number(targetValue) > max) {
      targetValue = max;
    } else if (Number(targetValue) < min) {
      targetValue = min;
    }
  }
  return String(targetValue);
}

/**
 * @description 字符串是utf-8编码，一个汉字三个字节，一个字母一个字节。maxlenByBytef是不是根据字节校验长度默认是false 
 * @param value  需要校验的字符
 * @param maxlength 最大长度
 * **/
function checkLength(value: string, maxlength, maxlenByByte: boolean = false) {
  let sum = 0;
  for (let i = 0; i < value.length; i++) {
    if ((value.charCodeAt(i) > 0) && (value.charCodeAt(i) < 255) || !maxlenByByte) {
      sum = sum + 1;
    } else {
      sum = sum + 3;
    }
    if (sum > maxlength) {
      return { sum, end: i }
    }
  }
  return { sum, end: value.length };
}


